package com.ilink.teacherservice.mapper.Screen;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;

@Mapper
public interface CourseStatisticsMapper {

    /**
     * 根据条件进行聚类和统计，支持过去1天、7天和30天的范围，并根据type参数返回对应字段的数据。
     *
     * @param courseId 课程ID，用于筛选和分组
     * @param chapterId 章节ID，用于筛选和分组
     * @param fileId 文件ID，用于筛选和分组
     * @param teacherId 教师ID，用于筛选和分组
     * @param time 日期范围，指定查询的起始日期
     * @param type 查询的字段类型，对应播放时长（study_duration）、播放量（study_num）或学生人数（student_num）
     * @return 查询结果，包含总量和每天的数量
     */
    @Select({
            "<script>",
            "SELECT ",
            "  SUM(",
            "    CASE ",
            "      WHEN #{type} = '播放时长' THEN study_duration ",
            "      WHEN #{type} = '播放量' THEN study_num ",
            "      WHEN #{type} = '学生人数' THEN student_num ",
            "    END ",
            "  ) AS totalValue, ",
            "  DATE(`time`) AS recordDate, ",
            "  SUM(",
            "    CASE ",
            "      WHEN #{type} = '播放时长' THEN study_duration ",
            "      WHEN #{type} = '播放量' THEN study_num ",
            "      WHEN #{type} = '学生人数' THEN student_num ",
            "    END ",
            "  ) AS dailyValue ",
            "FROM tb_screen ",
            "WHERE 1=1 ",
            "  AND `time` >= DATE_SUB(CURDATE(), INTERVAL ",
            "    CASE WHEN #{time} = 30 THEN 30 ELSE 7 END DAY) ",
            "<if test='courseId != null'>",
            "  AND course_id = #{courseId} ",
            "</if>",
            "<if test='chapterId != null'>",
            "  AND chapter_id = #{chapterId} ",
            "</if>",
            "<if test='fileId != null'>",
            "  AND file_id = #{fileId} ",
            "</if>",
            "<if test='teacherId != null'>",
            "  AND teacher_id = #{teacherId} ",
            "</if>",
            "GROUP BY recordDate ",
            "ORDER BY recordDate DESC ",
            "</script>"
    })
    List<Map<String, Object>> getStatistics(
            @Param("courseId") Long courseId,
            @Param("chapterId") Long chapterId,
            @Param("fileId") Long fileId,
            @Param("teacherId") String teacherId,
            @Param("time") Integer time,
            @Param("type") String type
    );
}
